<template>
  <j-modal :title="title" :width="800" :visible="visible" :confirmLoading="confirmLoading" switchFullscreen
    @ok="handleOk" @cancel="handleCancel" cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="客户">
          <a-select show-search placeholder="请选择" style="width: 100%" :filter-option="false"
            :not-found-content="fetching ? undefined : null" @search="getcusIdOptions" @change="handleChangeCus"
            disabled v-decorator="['cusId', { rules: [{ required: true, message: '请选择客户!' }] }]">
            <a-select-option v-for="t in cusIdOptions" :key="t.value">{{t.text}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="产品" prop="name">
          <pro-select type=1 disabled v-decorator="['productId', { rules: [{ required: true, message: '请选择产品!' }] }]"
            @change="proChange($event)" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="销售">
          <j-dict-select-tag disabled v-decorator="['userId', { rules: [{ required: true, message: '请选择用户!' }]}]"
            placeholder="请选择用户" :triggerChange=true dictCode="sys_user,realname,id,sales=1" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="联系方式">
          <a-input disabled v-decorator="['mobile', { }]"/>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="销售价格">
          <a-input-number disabled v-model="model.price" />元
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="定金价格">
          <a-input-number disabled v-model="model.prePrice" />元
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="尾款价格">
          <a-input-number disabled v-model="model.afterPrice" />元
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="施工日期">
          <j-date disabled v-decorator="[ 'workingTime', {}]"></j-date>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="备注">
          <a-textarea disabled v-decorator="[ 'remark', {}]"></a-textarea>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="订单状态">
          <j-dict-select-tag disabled v-decorator="[ 'state', {}]" title="状态" dictCode="orderState" placeholder="请选择"
            :triggerChange=true :disabled=isChangeStete />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="销售分成比例">
          <a-input-number disabled v-model="model.rate" />%
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="分成金额">
          <a-input-number disabled v-model="model.perfPrice" />
        </a-form-item>

      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
  import {
    httpAction,
    getAction
  } from '@/api/manage'
  import pick from 'lodash.pick'
  import moment from "moment"
  import debounce from 'lodash/debounce';
  import ProSelect from '@/views/crm/comp/ProSelect'
  import JDate from '@/components/jeecg/JDate'
  import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'

  export default {
    name: "OrderSingleModal",
    components: {
      ProSelect,
      JDate,
      JDictSelectTag,
    },
    data() {
      this.lastFetchId = 0;
      this.getcusIdOptions = debounce(this.getcusIdOptions, 800);
      return {
        cusIdOptions: [],
        productIdOptions: [],
        missionList: [],
        proMissionList: [],
        fetching: false,
        title: "操作",
        visible: false,
        isChangeStete:false,
        model: {
          price: 0,
          prePrice: 0,
          afterPrice: 0,
          perfPrice: 0,
          rate: 0,
        },
        labelCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 5
          },
        },
        wrapperCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 16
          },
        },

        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules: {},
        url: {
          add: "/crm/orderSingle/add",
          edit: "/crm/orderSingle/edit",
          getcusId: "/crm/cus/getcusId",
          getproductId: "/crm/product/getproductId",
        },
      }
    },
    created() {
      this.getcusIdOptions();
      this.listMission();
    },
    computed: {
      getPrice: function() {
        return this.model.price;
      },
      getPrePrice: function() {
        return this.model.prePrice;
      },

    },
    watch: {
      getPrice: {
        handler: function() {
          this.culPrice();
          this.culRate();
        }
      },
      getPrePrice: {
        handler: function() {
          this.culPrice();
        }
      }
    },
    methods: {
      look(record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.isChangeStete=this.model.state===3;
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'productId', 'userId', 'cusId', 'price', 'mobile', 'createId',
            'workingTime', 'remark', 'state'))
          //时间格式化
        });

      },
      close() {
        this.$emit('close');
        this.visible = false;
      },
      handleOk() {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if (!this.model.id) {
              httpurl += this.url.add;
              method = 'post';
            } else {
              httpurl += this.url.edit;
              method = 'put';
            }
            let formData = Object.assign(this.model, values);
            //时间格式化

            console.log(formData)
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('ok');
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
        })
      },
      handleCancel() {
        this.close()
      },
      culPrice() {
        if (this.model.price != undefined && this.model.prePrice != undefined) {
          this.model.afterPrice = this.model.price - this.model.prePrice;
        } else {
          this.model.afterPrice = 0;
        }
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      getSaleId(value) {
        let param = {
          id: value
        };
        getAction('/crm/cus/queryById', param).then((res) => {
          if (res.success) {
            this.model.userId = res.result.ownerUserId;
            this.model.mobile = res.result.mobile;
            this.form.setFieldsValue(pick(this.model, 'userId','mobile'))
          } else {
            that.$message.warning(res.message)
          }

        })
      },
      handleChangeCus(value) {
        console.log(`selected ${value}`);
        this.getSaleId(value);
      },
      getcusIdOptions(value) {
        console.log('getcusIdOptions', value);
        this.lastFetchId += 1;
        const fetchId = this.lastFetchId;
        this.cusIdOptions = [];
        this.fetching = true;
        let param = {
          mobile: value
        };
        getAction(this.url.getcusId, param)
          .then((res) => {
            if (fetchId !== this.lastFetchId) {
              return;
            }
            if (res.success) {
              this.cusIdOptions = res.result;
            } else {
              that.$message.warning(res.message)
            }
            this.fetching = false;
          })
      },

      listMission(value) {
        getAction('/crm/missionSingle/listMission').then((res) => {
          if (res.success) {
            this.missionList = res.result;
          } else {
            that.$message.warning(res.message)
          }

        })
      },
      proChange(val) {
        console.log(val);
        this.proMissionList = this.missionList.filter(item => {
          return item.productId === val;
        })
        this.culRate();
      },
      culRate() {
        this.model.rate = 0;
        if (this.proMissionList == undefined || this.proMissionList.length == 0) {
          return;
        }
        for (var i = 0; i < this.proMissionList.length; i++) {
          var miss = this.proMissionList[i];
          if (this.model.price >= miss.price) {
            this.model.rate = miss.rate;
            this.model.perfPrice = this.model.price * (this.model.rate / 100);
            return;
          }
        }
      },
    }
  }
</script>

<style lang="less" scoped>

</style>
